package com.example.basic.cls;


import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.IndexColorModel;
import java.awt.image.WritableRaster;
import java.io.File;

public class Test {
    public static void main(String[] args) {
        File dir = new File(".");
        File[] listFiles = dir.listFiles(pathname -> pathname.getName().contains(".jpg") || pathname.getName().contains(".png"));

        System.out.println("Current Dir:" + dir.getAbsolutePath());
        File newDir = new File(dir, "output");
        if (!newDir.exists()) {
            newDir.mkdirs();
        }

        try {
            for (File file : listFiles) {
                String name = file.getName();
                String fileName = file.getName().substring(0, name.length() - 4);
                BufferedImage src = convertRGBAToIndexed(ImageIO.read(file));
                ImageIO.write(src, "bmp", new File(newDir, fileName + ".bmp"));
                System.out.println("sourceFile : " + file.getName() + "    targetFile : " + fileName + ".bmp   finish!!!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static BufferedImage convertRGBAToIndexed(BufferedImage src) {
        BufferedImage dest = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_BYTE_INDEXED);
        Graphics g = dest.getGraphics();
        g.setColor(new Color(231, 20, 189));

        // fill with a hideous color and make it transparent
        g.fillRect(0, 0, dest.getWidth(), dest.getHeight());
        dest = makeTransparent(dest, 0, 0);

        dest.createGraphics().drawImage(src, 0, 0, null);
        return dest;
    }

    public static BufferedImage makeTransparent(BufferedImage image, int x, int y) {
        ColorModel cm = image.getColorModel();
        if (!(cm instanceof IndexColorModel))
            return image; // sorry...
        IndexColorModel icm = (IndexColorModel) cm;
        WritableRaster raster = image.getRaster();
        int pixel = raster.getSample(x, y, 0); // pixel is offset in ICM's palette
        int size = icm.getMapSize();
        byte[] reds = new byte[size];
        byte[] greens = new byte[size];
        byte[] blues = new byte[size];
        icm.getReds(reds);
        icm.getGreens(greens);
        icm.getBlues(blues);
        IndexColorModel icm2 = new IndexColorModel(8, size, reds, greens, blues, pixel);
        return new BufferedImage(icm2, raster, image.isAlphaPremultiplied(), null);
    }

}
